<template>
    <div class="pe-tabs">
        <div class="pe-tabs-header">
            <Scrollbar width="100%" type="horizontal" style="display: flex;align-items: center;">
                <div v-for="(item, index) in labelList" :ref="(el) => setItemRef(el)" class="pe-tabs-header-item"
                    :class="[index === activeIndex ? 'pe-tabs-header-active' : '']" @click="changeItem($event, index)">
                    {{ item
                    }}</div>
            </Scrollbar>
            <div class="pe-tabs-active-bar" :style="{ width: `${barWidth}px`, left: `${barLeft}px` }"></div>
        </div>
        <div ref="tabsContent" class="pe-tabs-content">
            <slot></slot>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, provide, onMounted, watch, nextTick } from 'vue'
import Scrollbar from '../scrollbar/scrollbar.vue';

const modelValue = defineModel<string | number>()

const tabsContent = ref<HTMLDivElement>()
const labelList = ref<string[]>([])
let nodeList: NodeListOf<HTMLDivElement>
// 选中的序号
const activeIndex = ref<number>(0)
// 标志数组
const nameList = ref<(string | number)[]>([])

const barWidth = ref<number>(0)
const barLeft = ref<number>(0)

let itemRefs: any[] = [];
const setItemRef = (el: any) => {
    if (el) {
        itemRefs.push(el);
    }
};

onMounted(() => {
    // nodeList = tabsContent.value!.querySelectorAll<HTMLDivElement>(".pe-tab-pane")
    // nodeList?.forEach((item, index) => {
    //     if (!item.id) {
    //         item.id = `pane-${index}`
    //     }
    //     if (nameList.value[index] === modelValue.value) {
    //         activeIndex.value = index
    //         item.style.display = ''
    //     } else {
    //         item.style.display = 'none'
    //     }
    // })
})

watch([nameList, labelList],() => {
    nextTick(() => {
        nodeList = tabsContent.value!.querySelectorAll<HTMLDivElement>(".pe-tab-pane")
        nodeList?.forEach((item, index) => {
            if (!item.id) {
                item.id = `pane-${index}`
            }
            if (nameList.value[index] === modelValue.value) {
                activeIndex.value = index
                item.style.display = ''
            } else {
                item.style.display = 'none'
            }
        })
        console.log(itemRefs);
    })
}, { immediate: true })

const changeItem = (event: any, index: number) => {
    activeIndex.value = index
    barWidth.value = event.target?.offsetWidth
    barLeft.value = event.target?.offsetLeft
    nodeList?.forEach((item, index1) => {
        if (index1 === index) {
            item.style.display = ''
        } else {
            item.style.display = 'none'
        }
    })
}

provide("pe-tabs-labelList", labelList)
provide("pe-tabs-nameList", nameList)
</script>

<script lang="ts">
export default {
    name: "pe-tabs"
}
</script>